package com.ugrow.ugrowcommunity.activity.seatReservation;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;

import com.github.gzuliyujiang.dialog.DialogConfig;
import com.github.gzuliyujiang.dialog.DialogStyle;
import com.github.gzuliyujiang.wheelpicker.OptionPicker;
import com.github.gzuliyujiang.wheelpicker.contract.OnOptionPickedListener;
import com.google.android.material.snackbar.Snackbar;
import com.google.gson.Gson;
import com.ugrow.ugrowcommunity.BuildConfig;
import com.ugrow.ugrowcommunity.R;
import com.ugrow.ugrowcommunity.activity.seatReservation.adapter.SeatAdapter;
import com.ugrow.ugrowcommunity.activity.seatReservation.bean.SeatBean;
import com.ugrow.ugrowcommunity.activity.seatReservation.dialog.ReservationFailDialog;
import com.ugrow.ugrowcommunity.activity.seatReservation.dialog.ReservationSuccessDialog;
import com.ugrow.ugrowcommunity.data.Data;
import com.ugrow.ugrowcommunity.databinding.ActivitySelectedSeatBinding;
import com.ugrow.ugrowcommunity.dialog.LoadProgressDialog;
import com.ugrow.ugrowcommunity.util.ArrayExistUtil;
import com.ugrow.ugrowcommunity.util.HttpUtil;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;

public class SelectedSeatActivity extends AppCompatActivity {

    private ActivitySelectedSeatBinding binding;
    private SeatAdapter adapter;
    private CheckBox selectSeat;
    private String time;
    private String day;
    private String[] lists;
    private String classroomID;
    private String classroomName;
    private String endTime;

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivitySelectedSeatBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        binding.back.setOnClickListener(v -> finish());

        Intent intent = getIntent();

        Bundle classRoomInfo = intent.getBundleExtra("classRoomInfo");

        if (classRoomInfo != null) {
            //教室名称
            classroomName = classRoomInfo.getString("classroomName");
            //教室ID
            classroomID = classRoomInfo.getString("classroomID");
            //被占座位
            lists = classRoomInfo.getStringArray("list");
            //开始日期
            day = classRoomInfo.getString("day");
            //预约开始开始时间
            time = classRoomInfo.getString("time");
        }

        binding.selectTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onOptionText();
            }
        });

        binding.classroom.setText("您正在预约[" + day + time + "]" + classroomName + classroomID + "-自习室座位");

        int spanCount = 8;
        adapter = new SeatAdapter(this, spanCount, 48, lists);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, spanCount);
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                if (adapter.isaBoolean(position)) {
                    return spanCount;
                } else return 1;
            }
        });
        binding.recyclerview.setLayoutManager(gridLayoutManager);
        binding.recyclerview.setAdapter(adapter);
        adapter.setOnItemClickListener(new SeatAdapter.OnItemClickListener() {
            @Override
            public void onClickListener(CheckBox checkBox, int position) {
                if (selectSeat != null && checkBox != selectSeat && selectSeat.isChecked()) {
                    selectSeat.setChecked(false);
                }
                selectSeat = checkBox;

                if (checkBox.isChecked()){
                    Snackbar.make(binding.myCoordinatorLayout, "正在选座 " + position, Snackbar.LENGTH_INDEFINITE)
                            .setAction("确定", v -> {
                                if (endTime == null || endTime.isEmpty()) {
                                    Toast.makeText(SelectedSeatActivity.this, "请选择结束时间！", Toast.LENGTH_SHORT).show();
                                    return;
                                }
                                LoadProgressDialog loadProgressDialog = new LoadProgressDialog(SelectedSeatActivity.this, "正在抢座中...", true);
                                loadProgressDialog.show();
                                HashMap<String, Object> map = new HashMap<>();
                                map.put("seatId", classroomID + position);
                                map.put("stuNum", Data.StuNum);
                                map.put("startTime", day + time);
                                map.put("endTime", day + endTime);
                                map.put("classroomId", classroomID);

                                Log.d("TAG", "seatId:" + classroomID + position);
                                Log.d("TAG", "stuNum:" + Data.StuNum);
                                Log.d("TAG", "startTime:" + day + time);
                                Log.d("TAG", "endTime:" + day + endTime);
                                Log.d("TAG", "classroomId:" + classroomID);
                                HttpUtil.httpPost(BuildConfig.SELECT_SEAT, map, HttpUtil.ContentType.JSON, new HttpUtil.CallBack() {
                                    @Override
                                    public void success(HttpUtil.Result result) {
                                        SeatBean seatBean = new Gson().fromJson(result.content, SeatBean.class);
                                        if (seatBean.getResult()) {
                                            loadProgressDialog.dismiss();
                                            new ReservationSuccessDialog(SelectedSeatActivity.this,
                                                    seatBean.getData().getStartTime() + ":00",
                                                    seatBean.getData().getEndTime() + ":00"      ,
                                                    seatBean.getData().getClassroomId(),
                                                    seatBean.getData().getSeatId(),
                                                    true)
                                                    .show();
                                        } else {
                                            loadProgressDialog.dismiss();
                                            new ReservationFailDialog(SelectedSeatActivity.this, seatBean.getMessage(), true).show();
                                        }
                                    }

                                    @Override
                                    public void failed(IOException e) {
                                        e.printStackTrace();
                                        loadProgressDialog.dismiss();
                                        Toast.makeText(SelectedSeatActivity.this, "网络连接异常，请检查网络连接！", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            })
                            .show();
                }else {
                    Snackbar.make(binding.myCoordinatorLayout, "取消选座 " + position, Snackbar.LENGTH_SHORT)
                            .setAction("确定", v -> {

                            })
                            .show();
                }
            }
        });


    }


    //页面跳转加信息传递
    public static void actionStart(Context context, Bundle bundle) {
        Intent intent = new Intent(context, SelectedSeatActivity.class);
        intent.putExtra("classRoomInfo", bundle);
        context.startActivity(intent);
    }

    //时间选择器
    public void onOptionText() {
        DialogConfig.setDialogStyle(DialogStyle.Three);//设置弹窗类型为从中间开始
        OptionPicker picker = new OptionPicker(this);
        String[] strings = {"6:00", "7:00", "8:00", "9:00", "10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00", "17:00", "18:00", "19:00", "20:00", "21:00"};
        int index = ArrayExistUtil.indexOf(strings, time);
        String[] array = Arrays.copyOfRange(strings, index + 1, strings.length);
        picker.setData(Arrays.asList(array));
        picker.setOnOptionPickedListener(new OnOptionPickedListener() {
            @Override
            public void onOptionPicked(int position, Object item) {
                endTime = (String) item;
                binding.selectTime.setText(endTime);

            }
        });
        picker.setTitle("结束时间");
        picker.getWheelView().setStyle(R.style.WheelDefault);
        picker.show();
    }
}